package cn.gan.loveofsoul.controller;

import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.commons.utils.StringUtils;
import cn.gan.loveofsoul.entity.User;
import cn.gan.loveofsoul.entity.constants.UserFlagEnum;
import cn.gan.loveofsoul.entity.constants.UserSexEnum;
import cn.gan.loveofsoul.entity.constants.StatusEnum;
import cn.gan.loveofsoul.entity.vo.UserVO;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.service.IUserService;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * @Description:
 * @Author: ganwh
 * @Since: 2023/10/9 15:33
 */
@RequestMapping("/appLogin")
@Controller
public class AppLoginController {
    private static final Logger logger = LogManager.getLogger(AppLoginController.class);

    @Autowired
    private IUserService userService;

    // 微信小程序相关
    private static final String WX_APPID = "wx64ec287efa64805d";
    private static final String WX_APPSECRET = "859bd65f067e7f8ffd9fcb41276d3d03";
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 功能描述: 微信小程序登录
     *
     * @param jsCode
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/10/10 18:01
     */
    @PostMapping("/wxLogin")
    @ResponseBody
    public Result wxLogin(@RequestBody String jsCode) {
        if (StringUtils.isBlank(jsCode)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", WX_APPID);
        paramMap.put("secret", WX_APPSECRET);
        paramMap.put("js_code", jsCode);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get(WX_LOGIN_URL, paramMap);
        JSONObject jsonObjectResult = JSON.parseObject(result, JSONObject.class);

        Result resultBody;
        if (Objects.nonNull(jsonObjectResult.get("errcode"))) {
            switch (jsonObjectResult.getInteger("errcode")) {
                case 40029:
                    logger.error("js_code无效");
                    resultBody = new Result(StatusCode.BAD_REQUEST, "js_code无效");
                    break;
                case 45011:
                    logger.error("API 调用太频繁，请稍候再试");
                    resultBody = new Result(StatusCode.ERROR, "API 调用太频繁，请稍候再试");
                    break;
                case 40226:
                    logger.error("高风险等级用户，小程序登录拦截");
                    resultBody = new Result(StatusCode.FORBIDDEN, "登录失败");
                    break;
                case -1:
                    logger.error("系统繁忙，此时请开发者稍候再试");
                    resultBody = new Result(StatusCode.ERROR, ErrorMessage.SYSTEM_ERROR);
                    break;
                default:
                    resultBody = new Result(StatusCode.ERROR, ErrorMessage.SYSTEM_ERROR);
            }
        } else {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getWxOpenId, jsonObjectResult.get("openid")).eq(User::getStatus, StatusEnum.NORMAL);
            User user = userService.getOne(wrapper);
            if (Objects.isNull(user)) {
                user = new User();
                user.setWxOpenId(jsonObjectResult.getString("openid"));
                user.setUserName("微信用户");
                user.setSex(UserSexEnum.SECRECY.getCode());
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                user.setStatus(StatusEnum.NORMAL.getCode());
                user.setFlag(UserFlagEnum.NORMAL.getCode());
                userService.save(user);
            }
            UserVO userVO = User.convert2UserVO(user);
            resultBody = new Result(StatusCode.SUCCESS, userVO);
        }
        return resultBody;
    }
}
